import {
	InformationBusinessCardList,
	InformationUserCodeLogin
} from '@/common/http/api.js'

/**
 * 登录 
 */
export function login({userId, shareId}) {
	return new Promise((res, rej) => {
		uni.login({
			provider: 'weixin',
			success: loginRes => {
				let data = {
					code: loginRes.code
				}
				if (userId) {
					data['share_userId'] = userId
				}
				if (shareId) {
					data['login_share_business_card_id'] = shareId
				}
				console.info('login', userId, shareId)
				InformationUserCodeLogin(data).then(d => {
					uni.setStorageSync("token", d.data.token)
					res()
				}).catch(err => {
					rej(err)
				})
			},
			fail(err) {
				console.error('login', err)
				rej(err)
			}
		});
	})
}

/**
 * 按钮登录
 * @param {Object} params 登录参数 userId, shareId
 * @param {Function} fn 登录后操作函数
 */
export async function LoginHandle (params,fn) {
	//默认领取code
	if (!uni.getStorageSync('token')) {
		await login(params)
	}
	
	//判断名片数量
	const r = await InformationBusinessCardList()
	const cardList = r.data
	
	if(!(Array.isArray(cardList) && cardList.length > 0)){
		//没有名片
		uni.reLaunch({
			url: '/pagesA/findInterest/findInterest?type=' + 1
		})
	} else {
		fn()
	}
}

/**
 * 是否领取
 * @param {Object} params 登录参数 userId, shareId
 * @return {Boolean} true 有名片 false 没有
 */
export async function isHasCardList (params) {
	//默认领取code
	// if (!uni.getStorageSync('token')) {
	// 	await login(params)
	// }
	
	if(!uni.getStorageSync('token')) return false
	
	//判断名片数量
	const r = await InformationBusinessCardList()
	const cardList = r.data
	return Array.isArray(cardList) && cardList.length > 0
}